package com.k.kpp.web.easyexcel2.controller;

import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.github.xiaoymin.knife4j.annotations.ApiSupport;
import com.k.kpp.web.util.EasyExcelUtils;
import com.k.kpp.web.easyexcel2.domain.ArrivePointExportVO;
import com.k.kpp.web.easyexcel2.domain.ExcelTypeEnum;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

@RestController
@ApiSupport(author = "ljw", order = 31)
@Api(tags = "Excel")
@Validated
@RequestMapping(value = "/excel/export")
public class ExportController {

    @ApiOperation(value = "数据导出 - 必达点")
    @ApiOperationSupport(order = 10)
    @RequestMapping(value = "/arrivePoint", method = RequestMethod.GET)
    public void arrivePoint(HttpServletResponse res, ArrivePointExportVO vo) throws IOException {
        // 获取导出数据
        List listExcel = new ArrayList();
        String excelType = "xx_excel";
        OutputStream os = res.getOutputStream();
        String expFilename = ExcelTypeEnum.ARRIVEPOINT.getName() + "_data_" + System.currentTimeMillis();
        setUpResponse(res, expFilename);
        ExcelTypeEnum.matchOpValue(excelType)
                .ifPresent(a -> EasyExcelUtils.exportExcel(os, a.getModelClass(), "sheet1", listExcel));
    }

    private void setUpResponse(HttpServletResponse res, String filename) {
        res.setContentType("application/octet-stream");
        res.setHeader("Cache-Control", "no-cache");
        res.setHeader("Pragma", "no-cache");
        res.setDateHeader("Expires", -1);
        res.setCharacterEncoding("UTF-8");
        res.setHeader("Content-disposition", String.format("attachment; filename=\"%s\"", filename + ".xlsx"));
    }
}